package com.langsin.action;

import com.langsin.service.UserLoginService;
import com.langsin.service.impl.UserLoginServiceImpl;
import com.langsin.vo.User;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class UserLoginAction extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String imageCode = request.getParameter("imageCode");
        HttpSession session = request.getSession();
        if(imageCode.equals(session.getAttribute("ImageCode"))){
            UserLoginService service = new UserLoginServiceImpl();
            User user = service.queryUserByNameAndPass(username,password);
            if(user == null){
                //请求转发 request域的生命周期
                request.setAttribute("errorInfo","用户名或密码不正确");
                request.getRequestDispatcher("./../login.jsp").forward(request,response);
            }else{
                //重定向
                session.setAttribute("user",user);
                response.sendRedirect("./loginok.jsp");
            }
        }else{
            request.setAttribute("errorInfo","验证码输入有误！");
            request.getRequestDispatcher("./../login.jsp").forward(request,response);
        }
    }
}
